<template>
  <div class="account-box">
    <div class="toggle">
      <a v-if="isMsgLogin" href="javascript:;" @click="isMsgLogin = false">
        <i class="icon icon-user"></i>使用账号登录
      </a>
      <a v-else href="javascript:;" @click="isMsgLogin = true">
        <i class="iconfont icon-msg"></i>使用短信登录
      </a>
    </div>
    <Form
      ref="formCom"
      v-slot="{ errors }"
      class="form"
      :validation-schema="mySchema"
      autocomplete="off"
    >
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field
              v-model="form.account"
              name="account"
              :class="{ error: errors.account }"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <div v-if="errors.account" class="error">
            <i class="iconfont icon-warning"></i>{{ errors.account }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field
              v-model="form.password"
              name="password"
              :class="{ error: errors.password }"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <div v-if="errors.password" class="error">
            <i class="iconfont icon-warning"></i>{{ errors.password }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              v-model="form.mobile"
              name="mobile"
              :class="{ error: errors.mobile }"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <div v-if="errors.mobile" class="error">
            <i class="iconfont icon-warning"></i>{{ errors.mobile }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field
              v-model="form.code"
              name="code"
              :class="{ error: errors.code }"
              type="password"
              placeholder="请输入验证码"
            />
            <span class="code" @click="send()">{{
              time === 0 ? '发送验证码' : `${time}秒后发送`
            }}</span>
          </div>
          <div v-if="errors.code" class="error">
            <i class="iconfont icon-warning"></i>{{ errors.code }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <!-- <RbtCheckout v-model="form.isAgree" /> -->
          <Field v-model="form.isAgree" :as="RbtCheckout" name="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login()">登录</a>
    </Form>
    <div class="action">
      <img
        src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
        alt=""
      />
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import RbtCheckout from '@/components/rbt-checkout.vue'
import Message from '@/components/Message'
import {
  userAccountLogin,
  userMobileLoginMsg,
  userMobileLogin
} from '@/api/user'
import useStore from '@/store'
import { useRoute, useRouter } from 'vue-router'
import { useIntervalFn } from '@vueuse/core'
import { UserInfo } from '@/types/user'
const route = useRoute()
const router = useRouter()
const { user, cart } = useStore()
// 是否短信登录
const isMsgLogin = ref(false)
// 表单信息对象
const form = reactive({
  isAgree: true,
  account: null,
  password: null,
  mobile: null,
  code: null
})

// 检验规则对象
const mySchema = reactive({
  account: schema.account,
  password: schema.password,
  mobile: schema.mobile,
  code: schema.code,
  isAgree: schema.isAgree
})

// 切换表单元素 还原数据和清除校验效果
const formCom = ref()
watch(
  () => isMsgLogin,
  () => {
    // 还原数据
    form.isAgree = true
    form.account = null
    form.password = null
    form.mobile = null
    form.code = null
    // 清除校验结果
    formCom.value.resetForm()
  }
)

// 需要在点击登录的时候对整体表单进行校验
const login = async () => {
  const valid = await formCom.value.validate()
  if (valid) {
    // 发送请求
    // 账号密码登录
    let data: UserInfo = {
      id: '',
      avatar: '',
      nickname: '',
      account: '',
      mobile: '',
      token: ''
    }
    try {
      if (!isMsgLogin.value) {
        const res = await userAccountLogin(form)
        data = res.data.result
        // userAccountLogin(form)
        //   .then(res => {
        //     // 1.存储信息
        //     const { id, account, nickname, avatar, token, mobile } =
        //       res.data.result
        //     user.setUserInfo({ id, account, nickname, avatar, token, mobile })
        //     // 2.提示
        //     Message({ type: 'success', text: '登录成功' })
        //     // 3.跳转
        //     router.push((route.query.redirectUrl as string) || '/')
        //   })
        //   .catch(e => {
        //     // 失败
        //     Message({
        //       type: 'error',
        //       text: e.response.data.message || '登录失败'
        //     })
        //   })
      } else {
        // 短信登录
        const res = await userMobileLogin(form)
        data = res.data.result
      }
      // 1.存储信息
      console.log(data, 'data')
      const { id, account, nickname, avatar, token, mobile } = data
      user.setUserInfo({ id, account, nickname, avatar, token, mobile })
      // 合并购物车信息
      await cart.mergeCart()
      Message({ type: 'success', text: '登录成功' })
      // 3.跳转
      router.push((route.query.redirectUrl as string) || '/')
    } catch (e: any) {
      Message({
        type: 'error',
        text: e.response.data.message || '登录失败'
      })
    }
  }
}

const time = ref(0)
const { pause, resume } = useIntervalFn(
  () => {
    time.value--
    if (time.value <= 0) {
      pause()
    }
  },
  1000,
  false
)
onUnmounted(() => {
  pause()
})

// 发送短信
const send = async () => {
  const valid = mySchema.mobile(form.mobile)
  if (valid) {
    if (time.value === 0) {
      await userMobileLoginMsg(form.mobile)
      Message({ type: 'success', text: '发送成功' })
      time.value = 60
      resume()
    }
  } else {
    formCom.value.setFieldError('mobile', valid)
  }
}
</script>

<style scoped lang="scss">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: $rbtColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: $priceColor;
          }
          &.active,
          &:focus {
            border-color: $rbtColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: $priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: $rbtColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
